package com.company.genealogy.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.genealogy.web.entity.User;
import com.company.genealogy.web.mapper.UserMapper;
import com.company.genealogy.web.service.RoleService;
import com.company.genealogy.web.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String userIdStr) throws UsernameNotFoundException {
        User user;
        
        // 尝试解析为Long类型的用户ID
        try {
            Long userId = Long.parseLong(userIdStr);
            user = userMapper.selectById(userId);
        } catch (NumberFormatException e) {
            // 如果不是数字，则按用户名查找
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", userIdStr);
            user = userMapper.selectOne(queryWrapper);
        }
        
        if (user == null) {
            throw new UsernameNotFoundException("User not found: " + userIdStr);
        }
        
        // 检查用户状态
        if (user.getStatus() != null && user.getStatus() != 1) {
            throw new UsernameNotFoundException("User is disabled: " + userIdStr);
        }
        
        // 获取所有角色
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        List<SimpleGrantedAuthority> authorities = roles.stream()
                .map(r -> new SimpleGrantedAuthority(r.getCode().toUpperCase()))
                .collect(Collectors.toList());
        
        // 添加用户类型权限
        if (user.getUserType() != null) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getUserType().toUpperCase()));
        }
        
        // 添加家族权限（如果用户属于某个家族）
        if (user.getClanId() != null) {
            authorities.add(new SimpleGrantedAuthority("CLAN_" + user.getClanId()));
        }
        
        // 添加分支权限（如果用户属于某个分支）
        if (user.getBranchId() != null) {
            authorities.add(new SimpleGrantedAuthority("BRANCH_" + user.getBranchId()));
        }
        
        return new org.springframework.security.core.userdetails.User(
                user.getId().toString(), // 使用用户ID作为principal
                user.getPasswordHash() != null ? user.getPasswordHash() : "",
                authorities
        );
    }
} 